package cn.yangliu.nacos.management.web.oauth2;

import java.util.List;

import cn.yangliu.nacos.comm.config.security.annotations.Authorize;
import cn.yangliu.nacos.comm.config.security.enums.Logic;
import cn.yangliu.nacos.management.entity.oauth2.Oauth2Authority;
import cn.yangliu.nacos.management.service.oauth2.Oauth2AuthorityService;
import cn.yangliu.operation.annotation.Action;
import cn.yangliu.operation.annotation.Module;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-01
 */
@RestController
@RequestMapping("/clientAuthority")
@Api(value = "客户端资源管理", tags = "客户端资源管理")
@Module("oauth2管理-客户端资源管理")
public class Oauth2AuthorityController {

    /**
     * current class instance's member.
     * The Authority service.
     */
    @Autowired
    private Oauth2AuthorityService authorityService;

    /**
     * current class instance's member.
     * The Discovery client.
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * Find all list.
     *
     * @return the list
     */
    @GetMapping("/findAll")
    @ApiOperation("查询所有资源")
    @Authorize(logic = Logic.OR,
            value = {"oauth2client:query","oauth2role:query",
                    "oauth2authority:query"})
    public List<Oauth2Authority> findAll() {
        return authorityService.findAll();
    }

    /**
     * Sync db int.
     *
     * @return the int
     */
    @PostMapping("/syncDb")
    @ApiOperation(("同步服务到数据库"))
    @Authorize("oauth2authority:sync")
    @Action("同步服务")
    public int syncDb() {
        List<String> services = discoveryClient.getServices();
        return authorityService.syncDb(services);
    }

    /**
     * Delete.
     *
     * @param id the id
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除服务")
    @Authorize("oauth2authority:delete")
    public void delete(@PathVariable("id") Long id) {
        authorityService.deleteById(id);
    }
}
